package com.sysu.minsysu.map;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.LocaleUtils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;
import com.sysu.minsysu.Main;
import com.sysu.minsysu.R;
import com.sysu.minsysu.utils.AcademyDialog;
import com.sysu.minsysu.utils.Utils;

public class ShowPositionsOnMap extends MapActivity{
	
	MapView mMapView;
	MapController mMapController;
	List<Overlay> mOverlays;
	
	ArrayList<PlaceInfo> mPlaceInfos;
	double[] mCenterPos;
	Bitmap[] mBitmaps;
	int mCount;
	
	Handler mHandler;
	GPSManager mGpsManager;

	private MyLocationOverlay me=null;

	@Override
	public void onCreate( Bundle savedInstanceState ){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map_campus);
		
		Bundle bundle = getIntent().getExtras();
		if( bundle!=null ){
			mPlaceInfos = (ArrayList<PlaceInfo>)bundle.getSerializable("infos");
			mCenterPos = bundle.getDoubleArray("centerPos");
			mCount = mPlaceInfos.size();
		}
		
		mMapView = (MapView)findViewById(R.id.mapview2);
		mMapController = mMapView.getController();
		
		mMapController.setCenter( Utils.getPoint(mCenterPos[0], mCenterPos[1]));
		mMapController.setZoom(17);
		mMapView.setBuiltInZoomControls(true);		

		mGpsManager = Main.mGpsManager;
		
		Drawable marker = getResources().getDrawable(R.drawable.marker);
		marker.setBounds(-marker.getIntrinsicWidth()/2, -marker.getIntrinsicHeight(), marker.getIntrinsicWidth()/2, 0);
		
		Toast.makeText(this, "点击地图上小标志即可获得该地点的详细信息", Toast.LENGTH_LONG).show();
		
		mOverlays = mMapView.getOverlays();
		mOverlays.add( new SitesOverlay(marker));

		me=new MyLocationOverlay(this, mMapView);
		mMapView.getOverlays().add(me);
		
		mHandler = new MyHandler();		
		
		
		if( mGpsManager.isGPSEnable() && mGpsManager.getCurrentLocation()==null ){
			Toast.makeText(this, "正在获取您的位置，请稍候……", Toast.LENGTH_SHORT).show();
			mHandler.sendEmptyMessageDelayed(0, 500);			
		}else if( mGpsManager.isGPSEnable() && mGpsManager.getCurrentLocation()!=null ){
			setCurLocation(mGpsManager.getCurrentLocation());
		}
	}
	
	@Override
	public void onResume() {
		super.onResume();
		
		me.enableCompass();
	}	
	
	@Override
	public void onPause() {
		super.onPause();
		
		me.disableCompass();
	}	

	private class MyHandler extends Handler{
		@Override
		public void handleMessage( Message message ){
			if( message.what == 0 ){
				if( mGpsManager!=null ){
					if( mGpsManager.getCurrentLocation()==null )				
						sendEmptyMessageDelayed(0, 500);
					else {
						setCurLocation( mGpsManager.getCurrentLocation() );
						mHandler.removeMessages(0);
					}
				}
			}
		}
	}
	
	private void setCurLocation( Location location){
		GeoPoint point = Utils.getPoint(location.getLatitude(), location.getLongitude());
		mMapView.getOverlays().add( new  MyLocationMarker( point, BitmapFactory.decodeResource(getResources(), R.drawable.mylocation)) );
	}
	
	private class MyLocationMarker extends Overlay{
		private GeoPoint point = null;
		private Bitmap pic=null;
		
		public MyLocationMarker( GeoPoint point, Bitmap bitmap ){
			this.point = point;
			pic = bitmap;
		}
		
		@Override
		public void draw( Canvas canvas, MapView mapView, boolean shadow ){
			if( !shadow ){
				Projection projection = mapView.getProjection();
				if( pic!=null ){
					Point pos = projection.toPixels(point, null);
					canvas.drawBitmap(pic, pos.x, pos.y, null );
				}
			}
		}
		
		@Override 
		public boolean onTap( GeoPoint point, MapView mapView ){
			Toast.makeText(ShowPositionsOnMap.this, "My Location:"+ point.getLongitudeE6() + " " + point.getLatitudeE6(), Toast.LENGTH_SHORT).show();
			return true;
		}
		
		
	}
	
	class SitesOverlay extends ItemizedOverlay<OverlayItem>{
		List<OverlayItem> items = new ArrayList<OverlayItem>();
		Drawable mMarket = null;
		OverlayItem inDragItem;
		
		public SitesOverlay( Drawable marker ){
			super(marker);
			mMarket = marker;
			try{
				for( int i=0; i < mCount; i++ ){
					PlaceInfo info = mPlaceInfos.get(i);
					OverlayItem item = new OverlayItem(Utils.getPoint(info.getLatitude(), info.getLongitude()), info.getName(), info.getIntro());
					items.add( item );
				}
			}catch (Exception e) {
				items.clear();
				Toast.makeText(ShowPositionsOnMap.this, "传送数据出错", Toast.LENGTH_SHORT).show();
			}
			populate();
		}

		@Override
		protected OverlayItem createItem(int i) {
			return items.get(i);
		}

		@Override
		public int size() {
			return items.size();
		}
		
		@Override
		public boolean onTouchEvent( MotionEvent event, MapView mapView ){
			final int action = event.getAction();
			final int x = (int)event.getX();
			final int y = (int)event.getY();
			boolean result = false;
			
			if( action == MotionEvent.ACTION_DOWN ){
				for( OverlayItem item : items ){
					Point point = new Point(0, 0);
					
					mMapView.getProjection().toPixels(item.getPoint(), point);
					
					if( hitTest(item, mMarket, x-point.x, y-point.y)){
						result = true;
						inDragItem = item;
					}
				}
				if( result=false)
					inDragItem=null;
			}else if ( action == MotionEvent.ACTION_UP && inDragItem!=null ) {
				for( int k=0; k<items.size(); k++ ){
					OverlayItem item = items.get(k);
					Point point = new Point();
					mMapView.getProjection().toPixels(item.getPoint(), point);
					if( hitTest(item, mMarket, x-point.x, y-point.y) && item==inDragItem){
						inDragItem=null;
						if( mBitmaps!=null ){
							for( int i=0; i<mBitmaps.length; i++ ){
								mBitmaps[i].recycle();
							}
						}
						PlaceInfo info = mPlaceInfos.get(k);
						int[] bitmapRes = info.getBitmaps();
						if( bitmapRes!=null ){
							mBitmaps = new Bitmap[ bitmapRes.length];
							for( int i=0; i<bitmapRes.length; i++ ){
								mBitmaps[i] = BitmapFactory.decodeResource(getResources(), bitmapRes[i]);
							}
						}else {
							mBitmaps=null;
						}
						AcademyDialog dialog = new AcademyDialog(ShowPositionsOnMap.this, item.getTitle(), item.getSnippet(), mBitmaps);
						dialog.show();
						result = true;
						break;
					}
				}
				inDragItem=null;
			}else if ( action == MotionEvent.ACTION_MOVE && inDragItem!=null ) {
				result=true;
			}
			
			return (result || super.onTouchEvent(event, mapView));
		}
	}
	
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	
}
